<template>

  <div class="pipleline">

    <el-row>
      <!-- 左侧侧边栏 -->
      <el-col :span="3">
        <el-card class="sidebar-card" shadow="hover">

          <el-table
              style="width:100%;font-size:12px;margin-bottom:10px;"
              :data="jenkinsviewsdata">
            <el-table-column width="20"></el-table-column>
            <el-table-column align="center" min-width="120" label="视图列表">
              <template v-slot="scope">
                <el-button type="text"  @click="jenkinsjoblist(scope.row)" >
                  <el-tag  type="primary">{{ scope.row }}</el-tag>
                </el-button>
              </template>
            </el-table-column>
          </el-table>



        </el-card>
      </el-col>

      <!-- 头部2，创建按钮 及搜索框 -->
      <el-col :span="21">
        <el-card class="Server-head-card" shadow="never" :body-style="{padding:'10px'}">
          <!-- float属性，会将多个同级标签放在同一行 -->
          <div style="float: left;margin-right:10px;">
            <el-button  size="small" type="primary" icon="Edit"  @click="createhostpipDrawer = true">新建流水线</el-button>
          </div>
          <div>
            <el-input class="Server-head-search" size="small" clearable placeholder="请输入" v-model='searchValue'></el-input>
            <el-button size="small" type="primary" plain icon="Edit" @click="jenkinsjoblist()">搜索</el-button>
<!--            <el-button size="small" type="primary" plain icon="Edit" @click="jenkinsjoblist()">刷新</el-button>-->
          </div>
        </el-card>

        <div>
          <el-card class="Server-body-card" shadow="never" :body-style="{padding:'5px'}">
            <el-table
                style="width:100%;font-size:12px;margin-bottom:10px;"
                :data="jenkinsjobsdata"
                v-loading="appLoading">
              <el-table-column width="20"></el-table-column>
              <el-table-column align="center" min-width="120" label="流水线名称">
                <template v-slot="scope">
                  <el-button type="text" >
                    <el-tag  type="primary">{{ scope.row.Name }}</el-tag>
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="100" label="状态">
                <template v-slot="scope">
                  <el-tag type="success" v-if="scope.row.Status === 'SUCCESS'">{{ scope.row.Status }}</el-tag>
                  <el-tag type="danger" v-else-if="scope.row.Status === 'FAILURE'">{{ scope.row.Status }}</el-tag>
                  <el-tag type="danger"  v-else-if="scope.row.Status === 'InitError'">初始化失败或未执行</el-tag>
                  <el-tag type="info"  v-else-if="scope.row.Status === 'ABORTED'">取消部署</el-tag>
                  <el-tag type="warning" v-else>执行中</el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="100" label="代码源">
                <template v-slot="scope">
                  <el-tag type="success">{{scope.row.Engineering}}</el-tag>
                  <br />
                  <br />
                  <el-tag type="success">{{scope.row.SourceBranch}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="50" label="触发方式">
                <template v-slot="scope">
                  <el-tag type="primary">{{ scope.row.TriggerMode }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="150" label="构建阶段">
                <template v-slot="scope">
                  <el-steps :active="computeActiveStepCount(scope.row.Test)"  align-center>
                    <el-step
                        v-for="stage in scope.row.Test"
                        :key="stage.isNil"
                        :title="stage.isNil"
                        :status="isLastStep(index, scope.row.Test) ? 'error' : ''"
                    />
                  </el-steps>
                </template>
              </el-table-column>
              <el-table-column align=center min-width="80" label="构建ID">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.BuildId }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align=center label="操作" min-width="150">
                <template v-slot="scope">
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="jenkinsrunjob(scope.row.Name,scope.row.BuildId,scope.row.TriggerMode,scope.row.Test)" >执行</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="joblist(scope.row.Name)" >查看历史</el-button>

                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="jenkinsstopjob(scope.row.Name,scope.row.BuildId)" >停止</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="jenkinsconfigjson(scope.row.Name,scope.row.BuildId)">编辑</el-button>
                  <el-button size="small" style="border-radius:5px;" icon="Edit" type="danger"  plain @click="deletejob(scope.row.Name)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                class="Server-body-pagination"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pagesizeList"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :prev-click="getServers"
                :total="ServerTotal">
            </el-pagination>
          </el-card>
        </div>
      </el-col>

    </el-row>
    <!-- 创建传统jenkins流水线-->
    <el-drawer
        v-model="createhostpipDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="新建传统流水线配置"
        size="50%">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="createhostpipData"  :rules="createhostpipRules" :model="createhostpipData" label-width="200px">
              <!-- prop用于rules中的校验规则的key -->

              <el-form-item class="deploy-create-form" label="流水线名称" prop="jobname" >
                <el-input v-model="createhostpipData.jobname"></el-input>
              </el-form-item>

              <el-form-item class="deploy-create-form" label="部署环境" prop="selectedEnv">
                <el-select v-model="createhostpipData.selectedEnv" filterable placeholder="请选择环境">
                  <el-option
                      v-for="env in envs"
                      :key="env"
                      :label="env"
                      :value="env">
                  </el-option>

                </el-select>
              </el-form-item>

              <el-radio-group v-model="createhostpipDrawer">
                <el-radio label="convention">通用模版</el-radio>
<!--                <el-radio label="k8spipleline">容器模板配置</el-radio>-->
                <el-radio label="pipleline">自定义pipleline</el-radio>
              </el-radio-group>

              <el-form-item class="deploy-create-form" label="镜像区域" prop="imagesregion" v-if="createhostpipDrawer === 'convention'">
                <el-select v-model="imagesregion" placeholder="请选择你的区域" >
                  <el-option
                      v-for="(item, index) in regions"
                      :key="index"
                      :label="item"
                      :value="item"
                  ></el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="harbor项目名称，用来存放各个项目镜像">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>

              <el-form-item class="deploy-create-form" label="工程名称" prop="gitlistid" v-if="createhostpipDrawer === 'convention'">
                <el-select v-model="gitlistid" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in gitlist"
                      :key="index"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
                {{ getGitlistName() }}
              </el-form-item>

              <el-form-item class="deploy-create-form" label="分支" prop="branchelistdata" v-if="createhostpipDrawer === 'convention'">
                <el-select v-model="branchelistdata" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in branchelist"
                      :key="index"
                      :label="item.name"
                      :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item class="deploy-create-form" label="流水线节点(node lable)" prop="jenkinslistCIdata" v-if="createhostpipDrawer === 'convention'">
                <el-select v-model="createhostpipData.jenkinslistCIdata" filterable placeholder="请选择">
                  <el-option
                      v-for="item in jenkinslist"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>

                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="Jenkins运行node节点">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>

              </el-form-item>

              <el-form-item class="deploy-create-form" label="自定义编译命令" prop="CIcommand" v-if="createhostpipDrawer === 'convention'">
                <el-input
                    v-model="createhostpipData.CIcommand"
                    :rows="5"
                    type="textarea"
                    placeholder="Please input"
                />
              </el-form-item>

              <el-form-item class="deploy-create-form" label="部署节点(k8s节点)" prop="k8sNode" v-if="createhostpipDrawer === 'convention'">
                  <el-select v-model="k8sNode" filterable placeholder="请选择">
                    <el-option
                        v-for="(data, index) in k8sList"
                        :key="index.k8s_name"
                        :label="data.k8s_name"
                        :value="data.k8s_name">
                    </el-option>
                  </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="K8S访问API证书文件名称，文件位置位于配置文件总设置config.conf">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>


              <el-form-item class="deploy-create-form" label="yaml文件(可选)" prop="yamllist" v-if="createhostpipDrawer === 'convention' ">
                <el-select v-model="UpdateJenkinsConfigData.yamllist" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in k8sYamlList"
                      :key="index"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="默认为代码库YAML文件或手动指定文件，手动指定文件请在对应目录中创建文件">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>

              <!-- JSON form item -->
              <el-form-item class="deploy-create-form" label="JenkinsPipleline" prop="customcommands" v-if="createhostpipDrawer === 'pipleline'">
                <el-input
                    v-model="createhostpipData.piplelinedata"
                    :rows="10"
                    type="textarea"
                    placeholder="Please input"
                />
              </el-form-item>

            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="createhostpipDrawer=false">取消</el-button>
        <el-button type="primary" @click="submitForm('createhostpipData')">创建流水线</el-button>

      </template>
    </el-drawer>
    <!-- 修改 -->
    <el-drawer
        v-model="updataserverDrawer"
        direction="rtl"
        :before-close="handleClose"
        title="修改传统流水线配置"
        size="50%">
      <template #default>
        <!-- flex布局,居中 -->
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <!-- ref绑定控件后，js中才能用this.$ref获取该控件 -->
            <!-- rules 定义form表单校验规则 -->
            <el-form ref="createhostpipData"  :rules="createhostpipRules" :model="UpdateJenkinsConfigData" label-width="200px">
              <!-- prop用于rules中的校验规则的key -->


              <el-form-item class="deploy-create-form" label="流水线名称" prop="jobname" >
                <el-input v-model="jenkinsconfigData.jobname"   disabled></el-input>
              </el-form-item>

              <el-form-item class="deploy-create-form" label="部署环境" prop="selectedEnv">
                <el-select v-model="UpdateJenkinsConfigData.selectedEnv" filterable placeholder="请选择环境">
                  <el-option
                      v-for="env in envs"
                      :key="env"
                      :label="env"
                      :value="env">
                  </el-option>

                </el-select>
              </el-form-item>


              <el-radio-group v-model="updataserverDrawer">
                <el-radio label="convention">通用模板</el-radio>
                <el-radio label="pipleline">自定义pipleline</el-radio>
              </el-radio-group>


              <el-form-item class="deploy-create-form" label="镜像区域" prop="imagesregion" v-if="updataserverDrawer === 'convention'">
                <el-select v-model="imagesregion" placeholder="请选择你的区域" >
                  <el-option
                      v-for="(item, index) in regions"
                      :key="index"
                      :label="item"
                      :value="item"
                  ></el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="harbor项目名称，用来存放各个项目镜像">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>


              <el-form-item class="deploy-create-form" label="工程名称" prop="gitlistid" v-if="updataserverDrawer === 'convention'">
                <el-select v-model="gitlistid" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in gitlist"
                      :key="index"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
                {{ getGitlistName() }}
              </el-form-item>

              <el-form-item class="deploy-create-form" label="分支" prop="branchelistdata" v-if="updataserverDrawer === 'convention'">
                <el-select v-model="branchelistdata" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in branchelist"
                      :key="index"
                      :label="item.name"
                      :value="item.name">
                  </el-option>
                </el-select>
              </el-form-item>


              <el-form-item class="deploy-create-form" label="流水线节点(node lable)" prop="jenkinslistCIdata" v-if="updataserverDrawer === 'convention'">
                <el-select v-model="UpdateJenkinsConfigData.jenkinslistCIdata" filterable placeholder="请选择">
                  <el-option
                      v-for="item in jenkinslist"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="Jenkins运行node节点">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>

              <el-form-item class="deploy-create-form" label="自定义编译命令" prop="CIcommand" v-if="updataserverDrawer === 'convention'">
                <el-input
                    v-model="UpdateJenkinsConfigData.CIcommand"
                    :rows="5"
                    type="textarea"
                    placeholder="Please input"
                />
              </el-form-item>

              <el-form-item class="deploy-create-form" label="部署节点(k8s节点)" prop="k8sNode" v-if="updataserverDrawer === 'convention'">
                <el-select v-model="k8sNode" filterable placeholder="请选择">
                  <el-option
                      v-for="(data, index) in k8sList"
                      :key="index.k8s_name"
                      :label="data.k8s_name"
                      :value="data.k8s_name">
                  </el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="K8S访问API证书文件名称，文件位置位于配置文件总设置config.conf">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>

              <el-form-item class="deploy-create-form" label="yaml文件(可选)" prop="yamllist" v-if="updataserverDrawer === 'convention' ">
                <el-select v-model="UpdateJenkinsConfigData.yamllist" filterable placeholder="请选择">
                  <el-option
                      v-for="(item, index) in k8sYamlList"
                      :key="index"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
                <el-popover
                    placement="top"
                    :width="200"
                    trigger="hover"
                    content="默认为代码库YAML文件或手动指定文件，手动指定文件请在对应目录中创建文件">
                  <template #reference>
                    <el-icon style="width:2em;font-size:18px;color:#4795EE"><WarningFilled/></el-icon>
                  </template>
                </el-popover>
              </el-form-item>


              <!-- JSON form item -->
              <el-form-item class="deploy-create-form" label="JenkinsPipleline" prop="customcommands" v-if="updataserverDrawer === 'pipleline'">
                <el-input
                    v-model="jenkinsconfigData.piplelinedata"
                    :rows="30"
                    type="textarea"
                    placeholder="Please input"
                />
              </el-form-item>



            </el-form>
          </el-col>
        </el-row>
      </template>
      <!-- 插槽，抽屉footer -->
      <template #footer>
        <!-- 点击后赋值false，隐藏抽屉 -->
        <el-button @click="updataserverDrawer=false">取消</el-button>
        <el-button type="primary" @click="UpdateJenkinsConfig()">保存修改</el-button>

      </template>
    </el-drawer>
    <!-- 执行历史 -->
    <el-dialog v-model="dialogTableVisible" title="执行历史" width="1500">
      <el-table :data="joblistdata">

        <el-table-column align=center min-width="50" label="流水线名称">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.jobname }} </el-tag>
          </template>
        </el-table-column>

        <el-table-column align=center min-width="50" label="构建ID">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.jobid }} </el-tag>
          </template>
        </el-table-column>


        <el-table-column align=center min-width="50" label="执行分支">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.gitlist_name }} </el-tag>
          </template>
        </el-table-column>


        <el-table-column align=center min-width="50" label="触发方式">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.TriggerMode }} </el-tag>
          </template>
        </el-table-column>

        <el-table-column align=center min-width="50" label="执行时间">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.Timestamp }} </el-tag>
          </template>
        </el-table-column>

        <el-table-column align=center min-width="50" label="构建总时间">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.Duration }} </el-tag>
          </template>
        </el-table-column>

        <el-table-column align=center min-width="50" label="执行结果">
          <template v-slot="scope">
            <el-tag type="primary">{{ scope.row.status }} </el-tag>
          </template>
        </el-table-column>


        <el-table-column align=center label="操作" min-width="150">
          <template v-slot="scope">
            <el-button size="small" style="border-radius:5px;" icon="Edit" type="primary" plain @click="joblistdataconfig(scope.row.Piplelinedata)" >查看历史配置</el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>
    <el-dialog v-model="dialogTableconfig" title="执行配置" width="800">
        <el-form-item class="deploy-create-form" prop="customcommands">
          <el-input
              v-model="this.jenkinsjoblistdata.Piplelinedata"
              :rows="30"
              type="textarea"
              placeholder="Please input"
          />
        </el-form-item>
    </el-dialog>
  </div>

</template>

<script>
import common from "../../common/Config";
import httpClient from '@/request';
// import joblist from "@/views/release_server/pipleline/joblist";

export default {
  name: 'PipelineComponent',
  data() {
    return {

      k8sNode: "",
      k8sListUrl: common.k8sList,
      k8sList:[],
      k8slistData: {
        url:common.k8sinit,
        params: {
          pool:'',
        }
      },


      k8sYamlList: "",
      k8sYamlListUrl: common.k8sYamlList,

      //test
      dialogTableVisible: false,
      dialogTableconfig:false,
      joblistdataconfigswitch:false,


      socket: null,
      // buildStatus:"",
      // buildStatusdata:"",
      // runandstop:"",
      joblistdata:"",


      //gitlab工程列表
      gitlistid:"",
      gitlistname:"",
      gitlistgroup:"",
      gitlist: [],
      gitdata: {
        url: common.gitdata,
      },

      branchelistdata:"",
      branchelist: [],
      branchedata: {
        brancheID:"",
        url: common.branchedata,
      },

      //selectedEnv: '',
      envs: ['DEV', 'SIT', 'UAT', 'PREPROD'],

      //镜像区域选择
      imagesregion: "",
      regions: "",
      harbor :{
        Harbor_projects_url: common.harbor_projects,
        // Harbor_prepositories_url: common.harbor_prepositories,
        // Harbor_images_list_url: common.harbor_images_list,
        // data:{
        //   projectname:"",
        //   imagesname:"",
        // }
      },

      //编译服务器列表
      //jenkinslistCIdata:[],
      jenkinslist: [],
      jenkinsCIdata: {
        url: common.jenkinsnodes,
      },

      //部署服务器组列表
      //serverlistCDdata:[],
      serverCDList: [],
      serverCDdata: {
        url: common.serverList,
      },


      RunCD:"",


      //更新传统流水线
      UpdateJenkinsConfigDrawer: false,
      UpdateJenkinsConfigData: {
        url: common.jenkinsupdateconfig,
        jobname:"",
        branche:"",
        gitlistid: "",
        gitlistname:"",
        imagesregion:"",
        gitlistgroup:"",
        gitlisturl:"",
        selectedEnv:"",
        jenkinslistCIdata:"",
        CIcommand:"",
        serverlistCDdata:"",
        CDcommand:"",
        piplelinedata:"",
        jobid:"",
        yamllist:"",
        k8sNode:"",
      },

      jenkinsconfigDrawer: false,
      jenkinsconfigjsondata:"",
      jenkinsconfigData: {
        url: common.jenkinsgetconfig,
        jobname:"",
        piplelinedata:"",
      },

      createhostpipDrawer: false,
      createhostpipData: {
        url: common.jenkinsjobadd,
        jobname:"",
        branche:"",
        gitlistid: "",
        gitlistname:"",
        gitlistgroup:"",
        gitlisturl:"",
        selectedEnv:"DEV",
        imagesregion:"",
        jenkinslistCIdata:"",
        CIcommand:"",
        serverlistCDdata:"",
        CDcommand:"",
        piplelinedata:"",
        yamllist:"",
        k8sNode:"",
      },

      //jon列表
      jenkinsjobsdata:[],
      jenkinsjobs: {
        filter_name:"",
        view_name:"",
        url: common.jenkinsgetjobs,
      },

      jenkinsviewsdata:[],
      jenkinsviews: {
        url: common.jenkinsviews,
      },

      //job执行
      jenkinsrunjobdata: {
        jobname:"",
        jobid:"",
        gitlist_name:"",
        branche:"",
        triggermode:"",
        url: common.jenkinsjobrun,
      },

      //job停止
      jenkinsstopjobdata: {
        jobname:"",
        jobid:"",
        url: common.jenkinsjobstop,
      },

      //job列表
      jenkinsjoblistdata: {
        jobname:"",
        Piplelinedata:"",
        url: common.jenkinsjoblisturl,
      },




      //修改流水线配置
      updataserverDrawer: false,
      updateServerData: {
        url: common.serverUpdate,
        updategroupID:'',
      },

      //删除流水线
      deletejobData: {
        url: common.jenkinsdeletejob,
        jobname:'',
      },

      //编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10, 20, 30],
      searchValue: '',
      appLoading: false,
      authentication:'',
      hostCI_mode:'',
      hostCD_mode:'',
      k8sinstall_mode:'',
      ServerTotal: 0,



      //创建server的表单校验规则
      createhostpipRules: {
        jobname: [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        selectedEnv : [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        imagesregion : [{
          required: true,
          message: '请填写账号',
          trigger: 'change'
        }],
        gitlistid : [{
          required: true,
          message: '请填写密码',
          trigger: 'change'
        }],
        //CredentialList列表名称后面优化名称
        branchelistdata : [{
          required: true,
          message: '请填写凭据',
          trigger: 'change'
        }],
        jenkinslistCIdata  : [{
          required: true,
          message: '请填写凭据',
          trigger: 'change'
        }],
        CIcommand  : [{
          required: true,
          message: '请填写凭据',
          trigger: 'change'
        }],
        k8sNode : [{
          required: true,
          message: '请填写凭据',
          trigger: 'change'
        }],
        // yamllist : [{
        //   required: true,
        //   message: '请填写凭据',
        //   trigger: 'change'
        // }],
      },
    }
  },



  methods: {

    getk8slist() {
      httpClient.get(this.k8sListUrl)
          .then(res => {
            this.k8sList = res.data
            //console.log(this.k8sList)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },


    getyamllist() {
      httpClient.get(this.k8sYamlListUrl)
          .then(res => {
            this.k8sYamlList = res.data
            //console.log(this.k8sYamlList)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //harbor镜像区域
    harbor_projects() {
      httpClient.get(this.harbor.Harbor_projects_url)
          .then(res => {
            this.regions = res.data
            //console.log(this.regions)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    gitdatalist() {
      httpClient.get(this.gitdata.url, {params: this.gitdata})
          .then(res => {
            this.gitlist = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },


    branchedatalist() {
      httpClient.post(this.branchedata.url, this.branchedata)
          .then(res => {
            this.branchelist = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    jenkinsnodeslist() {
      httpClient.get(this.jenkinsCIdata.url, {params: this.jenkinsCIdata})
          .then(res => {
            this.jenkinslist = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },
    //查询当前流水线数据
    jenkinsjoblist(row) {

      this.jenkinsjobs.filter_name = this.searchValue
      this.jenkinsjobs.view_name = row
      // this.deploymentListData.params.limit = this.pagesize
      // this.deploymentListData.params.pool = this.k8sValue

      httpClient.get(this.jenkinsjobs.url,{params: this.jenkinsjobs})
          .then(res => {
            this.jenkinsjobsdata = res.data
            //console.log(this.jenkinsjobsdata)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    jenkinsviewslist() {
      httpClient.get(this.jenkinsviews.url)
          .then(res => {
            this.jenkinsviewsdata = res.data
            //console.log( this.jenkinsviews)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    jenkinsrunjob(jobName,jobid,triggermode) {
      this.updateJobStatus(jobName, '点击执行后状态变为执行中');
      this.jenkinsrunjobdata.jobname = jobName
      this.jenkinsrunjobdata.jobid = jobid
      this.jenkinsrunjobdata.triggermode = triggermode

      httpClient.post(this.jenkinsrunjobdata.url, this.jenkinsrunjobdata)
          .then(res => {
            this.$message.success({
              message: res.data
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    //点击执行后讲状态立马变为执行中
    updateJobStatus(jobName, newStatus) {
      // Find the job in your job list and update its status
      // This is a simplified example; your actual implementation may differ
      const job = this.jenkinsjobsdata.find(job => job.Name === jobName);
      if (job) {
        job.Status = newStatus;
      }
    },

    jenkinsstopjob(jobname,jobid){
      this.jenkinsstopjobdata.jobname = jobname
      this.jenkinsstopjobdata.jobid = jobid
      httpClient.post(this.jenkinsstopjobdata.url, this.jenkinsstopjobdata)
          .then(res => {
            this.$message.success({
              message: res.data
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },

    joblist(jobname){
      this.jenkinsjoblistdata.jobname = jobname
      httpClient.post(this.jenkinsjoblistdata.url, this.jenkinsjoblistdata)
          .then(res => {
            this.joblistdata = res.data
            //console.log(this.joblistdata)
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
      this.dialogTableVisible = true
    },

    joblistdataconfig(Piplelinedata){
      this.jenkinsjoblistdata.Piplelinedata = Piplelinedata
      //console.log(this.jenkinsjoblistdata.Piplelinedata)
      this.dialogTableconfig = true
    },

    //定义构建状态为SUCCESS位置
    computeActiveStepCount(testSteps) {
      let activeCount =  0;
      if (testSteps) {
        testSteps.forEach((stage) => {
          if (stage.Status === 'SUCCESS') {
            activeCount++;
          }
        });
      }
      return activeCount;
    },

    isLastStep(index, steps) {
      return index === steps.length -  1 && steps[index].Status !== 'SUCCESS';
    },

    serverCDlist() {
      httpClient.get(this.serverCDdata.url, {params: this.serverCDdata})
          .then(res => {
            this.serverCDList = res.data
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
    },


    getGitlistName() {
      // 使用 Optional Chaining 来安全地调用 .find()
      const selectedItem = this.gitlist?.find(item => item.id === this.gitlistid);

      if (selectedItem) {
        this.gitlistname = selectedItem.name;
        this.gitlistgroup = selectedItem.name_with_namespace;
        this.gitlisturl = selectedItem.http_url_to_repo;
        this.gitlisturl = this.gitlisturl.replace(/^http:\/\//i, '');
        //console.log(this.gitlisturl)
      } else {
        // 清除已设置的属性值，以防止未定义的情况
        this.gitlistname = '';
        this.gitlistgroup = '';
        this.gitlisturl = '';
      }
    },




    //创建
    createserverpipFunc() {
      this.createhostpipData.gitlistid = this.gitlistid
      this.createhostpipData.gitlistname = this.gitlistname
      this.createhostpipData.gitlistgroup = this.gitlistgroup
      this.createhostpipData.gitlisturl = this.gitlisturl
      this.createhostpipData.branche = this.branchelistdata
      this.createhostpipData.imagesregion = this.imagesregion
      this.createhostpipData.k8sNode = this.k8sNode


      //console.log(this.createhostpipData)
      httpClient.post(this.createhostpipData.url, this.createhostpipData)
          .then(res => {
            this.$message.success({
              message: res.msg

            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.createhostpipDrawer = false
            //console.log (this.createhostpipData)
            this.jenkinsjoblist()
          })
    },
    //提交表单，验证数据
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.createserverpipFunc()
        } else {
          return false
        }
      })
    },

    //查询编辑更新配置
    jenkinsconfigjson(jobname,jobid) {
      this.jenkinsconfigData.jobname = jobname
      this.jenkinsconfigData.jobid = jobid

      //console.log(this.jenkinsconfigData)
      httpClient.get(this.jenkinsconfigData.url, {params: {jobname: this.jenkinsconfigData.jobname}})
          .then(res => {
            // The response data is available in res.data
            this.jenkinsconfigData.piplelinedata = res.data;
          })
          .catch(error => {
            // Handle the error
            this.$message.error({
              message: error.message
            })
          })
          .finally(() => {
            this.updataserverDrawer = true
          })
    },

    UpdateJenkinsConfig() {
      this.UpdateJenkinsConfigData.jobname =  this.jenkinsconfigData.jobname
      this.UpdateJenkinsConfigData.gitlistid = this.gitlistid
      this.UpdateJenkinsConfigData.gitlistname = this.gitlistname
      this.UpdateJenkinsConfigData.imagesregion = this.imagesregion
      this.UpdateJenkinsConfigData.gitlistgroup = this.gitlistgroup
      this.UpdateJenkinsConfigData.gitlisturl = this.gitlisturl
      this.UpdateJenkinsConfigData.branche = this.branchelistdata
      this.UpdateJenkinsConfigData.piplelinedata = this.jenkinsconfigData.piplelinedata
      this.UpdateJenkinsConfigData.jobid = this.jenkinsconfigData.jobid
      this.UpdateJenkinsConfigData.k8sNode = this.k8sNode



      //console.log(this.UpdateJenkinsConfigData)
      //选择常规模式时清空流水线数据
      if (this.updataserverDrawer === 'convention') {
        this.UpdateJenkinsConfigData.piplelinedata = '';
      }

      httpClient.put(this.UpdateJenkinsConfigData.url, this.UpdateJenkinsConfigData)
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.updataserverDrawer = false
           // console.log(this.UpdateJenkinsConfigData)
          })
    },

    deletejob(jobname) {
      this.deletejobData.jobname =  jobname
      httpClient.delete(this.deletejobData.url, {data: this.deletejobData})
          .then(res => {
            this.$message.success({
              message: res.msg
            })
          })
          .catch(res => {
            this.$message.error({
              message: res.msg
            })
          })
          .finally(() => {
            this.jenkinsjoblist()
          })

    },

    ////实现jenkins流水线状态和平台实时同步////
    connect() {
      this.socket = new WebSocket('ws://localhost:8080/vue-webhook');

      this.socket.onopen = () => {
        this.status = 'Connected';
      };

      this.socket.onmessage = (event) => {
        console.log('Message from server:', event.data);
        this.jenkinsjoblist()
        // Handle the message as needed, for example, update the UI.

      };

      this.socket.onclose = () => {
        this.status = 'Disconnected';
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
      console.log("连接成功")
    },

    //分页属性
    handleSizeChange(size) {
      this.pagesize = size;
      this.getServers()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getServers()
    },
    //选择判断
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(() => {
            done();
          })
          .catch(() => {});
    },

    handleConfirm(obj, operateName, fn) {
      this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
      this.$confirm(this.confirmContent,'提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
          .then(() => {
            fn(obj)
          })
          .catch(() => {
            this.$message.info({
              message: '已取消操作'
            })
          })
    },
  },

  //注册子组件
  // components: {
  //   joblist,
  // },

  watch: {
    // 当 question 改变时，这个函数会被调用
    gitlistid: function () {
      this.branchedata.brancheID = this.gitlistid
      this.branchedatalist()
    },
    //this.jenkinsjobsdata
  },

  created() {
    this.gitdatalist()
    this.jenkinsnodeslist()
    this.serverCDlist()
    this.jenkinsjoblist()
    // this.checkBuildStatus()
    this.connect()
    this.jenkinsviewslist()
    this.harbor_projects()
    this.getk8slist()
    this.getyamllist()
  },
  // mounted() {
  // }
}

</script>

<style scoped>

.sidebar-card {
  height: 100vh; /* 设置侧边栏高度为视口高度 */
}




.Server-head-card,.Server-body-card {
  border-radius: 10px;
  margin-bottom: 20px;
}
.Server-head-search {
  width:160px;
  margin-right:10px;
}
/*.deploy-create-form  {*/
/*  width:  400px; !* Set the width as desired *!*/
/*  height: 400px; !* Set the height as desired *!*/
/*}*/


</style>